package cn.sciento.farm.devicemanager.common.util;

import java.util.Arrays;
import java.util.regex.Pattern;

/**
 * User: wumu
 * Date: 11/2/17
 * Time: 10:15 AM
 * @author wumu
 */
public class NumberUtil {

    static Pattern pattern = Pattern.compile("^[-]?[\\d]*$");

    public static boolean isPositiveInteger(String str) {
        if (str != null && !"".equals(str.trim())) {
            return str.matches("^[0-9]*$");
        }
        return false;
    }


    public static boolean isInteger(String str) {

        return pattern.matcher(str).matches();
    }

    public static Float double2float(double primitiveData, int digit) {
        return (float) ((Math.round(primitiveData * Math.pow(10, digit)) / Math.pow(10, digit)));
    }

    public static Double double2double(double primitiveData, int digit) {
        return  ((Math.round(primitiveData * Math.pow(10, digit)) / Math.pow(10, digit)));
    }

    public static Float float2float(float primitiveData, int digit) {
        return (float) ((Math.round(primitiveData * Math.pow(10, digit)) / Math.pow(10, digit)));
    }

    /**
     * 将byte转换为一个长度为8的byte数组，数组每个值代表bit
     */
    public static byte[] getBooleanArray(byte b) {
        byte[] array = new byte[8];
        for (int i = 7; i >= 0; i--) {
            array[i] = (byte) (b & 1);
            b = (byte) (b >> 1);
        }
        return array;
    }

    public static byte[] getBitArray(int b) {
        byte[] array = new byte[32];
        for (int i = 31; i >= 0; i--) {
            array[i] = (byte) (b & 1);
            b = (int) (b >> 1);
        }
        return array;
    }

    /**
     * 把byte转为字符串的bit
     */
    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }


    public static void main(String[] args) {
        int b = 2; // 0011 0101
        // 输出 [0, 0, 1, 1, 0, 1, 0, 1]
        System.out.println(Arrays.toString(getBitArray(b)));

    }

}
